package com.sgb.kjwl.viewmodel.home;

import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.google.gson.reflect.TypeToken;
import com.sgb.auction.base.BaseApi;
import com.sgb.auction.entity.AuctionListEntity;
import com.sgb.auction.entity.PublishListBean;
import com.sgb.auction.entity.RequestBean;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.api.service.BigHomeAPI;
import com.sgb.jicai.service.CentralizedMiningAPI;
import com.sgb.kjwl.api.service.GoodsAPI;
import com.sgb.kjwl.api.service.LookingforAJobAPI;
import com.sgb.kjwl.api.service.MaterialAPI;
import com.sgb.kjwl.api.service.PickAPI;
import com.sgb.kjwl.model.entity.DemandHallListEntity;
import com.sgb.jicai.entity.FactoryCentralizedListEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.SearchMaterialEntity3;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson3;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.kjwl.model.entity.user.BigHomeAndroidEntity;
import com.sgb.jicai.entity.FactoryCentralizedItemEntity;
import com.swgk.core.base.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.home.BigHomeFragment3;
import com.sgb.kjwl.view.ui.fragment.home.CommodityMaterialFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CommodityMaterialModel extends BaseViewModel {
    public HomeRepertory repertory;
    private CommodityMaterialFragment fragment;
    public ObservableField<MaterialFilterJson3> materialFilterJson = new ObservableField<>(new MaterialFilterJson3());
    public ObservableField<MaterialFilterJson3> materialFilterJson3 = new ObservableField<>(new MaterialFilterJson3());
    public ObservableField<MaterialFilterJson> materialFilterJson2 = new ObservableField<>(new MaterialFilterJson());
    private int mPageIndex;
    public int mPageSize = 3;
    private int PromoteStatus = 2;
    private String longitude;
    private String latitude;
    private int page = 1;

    public CommodityMaterialModel(CommodityMaterialFragment fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    /**
     * 获取type数据
     *
     * @param code
     */
    public void recomandCate(String code) {
        APIManager.getInstance(false, false).create(BigHomeAPI.class).recomandCate(repertory.getAreaCode(), code).enqueue(new ICallBack<BaseEntity<BigHomeAndroidEntity>>() {
            @Override
            public void onSuccess(BaseEntity<BigHomeAndroidEntity> data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (code.equals(BigHomeFragment3.MATERIAL)) {
                        List<MenuEntity> childList = data.getData().getTagList().get(0).getChildList();
                        MenuEntity menuEntity = new MenuEntity();
                        menuEntity.setName("全部");
                        menuEntity.setId("");
                        childList.add(0, menuEntity);
                        fragment.showTypeData(childList);
                    } else {
                        MToast.showToast(fragment.getActivity(), data.getMsg());
                    }
                }
            }
        });
    }

    /**
     * 精选的数据列表
     */
    public void getMaterialModel(String name, String id, boolean isLoadMore, int mItemType, boolean isRefresh) {
        if (repertory.getIsLocal()) {
            //经度
            latitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
            //纬度
            longitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
        } else {
            //经度
            longitude = repertory.getLongititude();
            //纬度
            latitude = repertory.getLatitude();
        }
        mPageIndex = isLoadMore ? mPageIndex + 1 : 1;
        if (mItemType == 4) {
            materialFilterJson.get().setSize(6);
            materialFilterJson.get().setSelfSupportTag("1");
        } else {
            materialFilterJson.get().setSize(6);
        }
        materialFilterJson.get().setPage(mPageIndex);
        materialFilterJson.get().setCid1(id);
        if (mItemType == 3) {
            materialFilterJson.get().setPromoteStatus(PromoteStatus);
        }
        materialFilterJson.get().setLon(String.valueOf(longitude));
        materialFilterJson.get().setLat(String.valueOf(latitude));
        materialFilterJson.get().setTimeSort(0);
        materialFilterJson.get().setDistanceSort("1");
//        materialFilterJson.get().setAreaCode(repertory.getAreaCode());
      /*  if (mPageIndex > 1) {
            DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        }*/
//        if (TextUtils.isEmpty(id)) {//id为空则是全部模块
//            getFirstPageGoods(id, mPageIndex, materialFilterJson.get(), mItemType, isRefresh);
//        } else {
//            getMaterialList3(materialFilterJson.get(), isRefresh);
//        }
        getMaterialList3(materialFilterJson.get(), isLoadMore, isRefresh, mItemType);
    }

    /**
     * 促销的数据列表
     */
    public void getMaterialModel2(String id, boolean isLoadMore, int mItemType, boolean isRefresh) {
        if (repertory.getIsLocal()) {
            //经度
            latitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
            //纬度
            longitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
        } else {
            //经度
            longitude = repertory.getLongititude();
            //纬度
            latitude = repertory.getLatitude();
        }
        mPageIndex = isLoadMore ? mPageIndex + 1 : 1;
        materialFilterJson3.get().setPage(mPageIndex);
        materialFilterJson3.get().setSize(6);
        materialFilterJson3.get().setCid1(id);
        materialFilterJson3.get().setPromoteStatus(PromoteStatus);
        materialFilterJson3.get().setLat(latitude);
        materialFilterJson3.get().setLon(longitude);
        materialFilterJson3.get().setTimeSort(0);
        materialFilterJson3.get().setDistanceSort("1");
        APIManager.getInstance(false, isRefresh).create(MaterialAPI.class).getMaterialList3(materialFilterJson3.get()).enqueue(new ICallBack<BaseEntity<ListResponse<List<SearchMaterialEntity3>>>>(true) {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<SearchMaterialEntity3>>> data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * /获取工程材料列表(现在商品列表)
     *
     * @param materialFilterJson3
     */
    private void getMaterialList3(MaterialFilterJson3 materialFilterJson3, boolean isLoadMore, boolean isRefresh, int mItemType) {
        boolean flag = materialFilterJson.get().getPage() == 1 && mItemType == 0 && TextUtils.isEmpty(materialFilterJson3.getCid1());
        APIManager.getInstance(flag, isRefresh).create(MaterialAPI.class).getMaterialList3(materialFilterJson3).enqueue(new ICallBack<BaseEntity<ListResponse<List<SearchMaterialEntity3>>>>(!flag, true) {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<SearchMaterialEntity3>>> data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 商砼的独立接口
     */
    public void getSTData(Boolean isLoadMore, int mItemType) {
        if (repertory.getIsLocal()) {
            //经度
            latitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
            //纬度
            longitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
        } else {
            //经度
            longitude = repertory.getLongititude();
            //纬度
            latitude = repertory.getLatitude();
        }
        mPageIndex = isLoadMore ? mPageIndex + 1 : 1;
        materialFilterJson2.get().setPageNum(mPageIndex);
//        materialFilterJson2.get().setAreaCode(repertory.getAreaCode());

        if (mItemType == 4) {
            materialFilterJson2.get().setSelfSupport("1");
            materialFilterJson2.get().setPageSize(6);
        } else {
            materialFilterJson2.get().setPageSize(mPageSize);
        }
        materialFilterJson2.get().setLon(longitude);
        materialFilterJson2.get().setLat(latitude);
        APIManager.getInstance().create(GoodsAPI.class).getHomeSTList(materialFilterJson2.get()).enqueue(new ICallBack<BaseEntity<ListResponse<List<SearchMaterialEntity3>>>>(true) {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<SearchMaterialEntity3>>> data) {
                fragment.showList(data.getData().getList(), isLoadMore);
            }
        });
    }

    /**
     * 供应商数据列表
     *
     * @param isLoadMore
     */
    public void getRecommandSupplier(boolean isLoadMore, boolean isRefresh) {
        Map map = new HashMap();
        mPageIndex = isLoadMore ? mPageIndex + 1 : 1;
//        map.put("areaCode", repertory.getAreaCode());
        map.put("page", mPageIndex);
        map.put("limit", 3);
        APIManager.getInstance(false, isRefresh).create(BigHomeAPI.class).getSupplierList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<SupplierRecommendEntity>>>>(true) {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<SupplierRecommendEntity>>> data) {
                if (data == null || data.getState() == null)
                    return;
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }


    //获取供货商地图数据
    public void getSupplierMapModel(boolean isLoadMore, boolean isRefresh) {
        if (repertory.getIsLocal()) {
            //经度
            latitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, ""))
                    ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "");
            //纬度
            longitude = "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, ""))
                    ? repertory.getLongititude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "");
        } else {
            //经度
            longitude = repertory.getLongititude();
            //纬度
            latitude = repertory.getLatitude();
        }
        Map map = new HashMap();
        mPageIndex = isLoadMore ? mPageIndex + 1 : 1;
//        map.put("areaCode", repertory.getAreaCode());
        map.put("page", mPageIndex);
        map.put("limit", 3);
        map.put("latitude", latitude);
        map.put("longitude", longitude);
        map.put("distance", 10000);
        map.put("current", mPageIndex);
        if (mPageIndex > 1) {
            DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        if (mPageIndex == 1 && fragment.getPosition() == 0) {
            Type type = new TypeToken<ListResponse<List<SupplierRecommendEntity>>>() {
            }.getType();
            Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.CaheMateialStlistcontent, type);
            if (obj != null && !isRefresh) {
                ListResponse<List<SupplierRecommendEntity>> listResponse = (ListResponse<List<SupplierRecommendEntity>>) obj;
                fragment.showList(listResponse.getList(), isLoadMore);
                return;
            }
        }
        repertory.getSupplierMapData(map)
                .subscribe(new Consumer<BaseEntity<ListResponse<List<SupplierRecommendEntity>>>>() {
                    @Override
                    public void accept(BaseEntity<ListResponse<List<SupplierRecommendEntity>>> data) throws Exception {
                        DialogHelper.dismissProgressDialog();
                        if (data == null || data.getState() == null)
                            return;
                        if (data.getState().equals(APIManager.RESPONSE_OK)) {
                            // 网络数据的HashMap值
                            String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                            String cacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CaheMateialStlistcontent);
                            if (mHashNet.equals(cacheOperationHash)) {
                                fragment.showList(data.getData().getList(), isLoadMore);
                                DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.CaheMateialStlistcontent, data.getData());
                            } else {
                                fragment.showList(data.getData().getList(), isLoadMore);
                            }
                        } else {
                            MToast.showToast(fragment.getActivity(), data.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        DialogHelper.dismissProgressDialog();
                        MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage());
                    }
                });

    }

    /**
     * 获取询价采购的数据列表信息
     *
     * @param userid
     * @param sortid
     * @param enquiryid
     * @param fcatName
     * @param searchname
     * @param isLoadMore
     */
    public void getDemandHallList(String userid, String sortid, String enquiryid, String fcatName, String searchname, boolean isLoadMore, boolean isRefresh) {
        mPageIndex = isLoadMore ? mPageIndex + 1 : 1;
        Map map = new HashMap();
        if (!TextUtils.isEmpty(userid)) {
            map.put("authMethod", userid);
        }
        map.put("limit", 3);
        map.put("page", mPageIndex);
        map.put("sortType", sortid);
        if (!TextUtils.isEmpty(enquiryid)) {
            map.put("status", enquiryid);
        }
        map.put("fcatName", fcatName + "");
        map.put("tcatName", searchname + "");
        NewAPIManager.getInstance().getGoodsAPI().getDemandHallList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<DemandHallListEntity>>>>(true) {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<DemandHallListEntity>>> data) {
                if (data == null)
                    return;
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (data.getData() == null)
                        return;
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 询价采购详情界面
     */
    public void showUrl(String no) {
        APIManager.getInstance().create(LookingforAJobAPI.class).getUrlSetting("enquiryDetail").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (!TextUtils.isEmpty(data.getData().getUrl())) {
                        String url = data.getData().getUrl() + "?no=" + no;
                        WebViewX5HostActivity.start(fragment.getActivity(), url);

                        //存储商品跳转h5标记
                        SharedPreferenceUtil.getInstance().saveString("EVENT_SHOPPING_TYPE", "event_shopping_list");
                    } else {
                        WebViewX5HostActivity.start(fragment.getActivity(), "");
                    }
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 供方发起列表
     */
    public void getFactoryCentralizedList(boolean b, boolean isRefresh, String firstType) {
        mPageIndex = b ? mPageIndex + 1 : 1;
        Map map = new HashMap();
        map.put("limit", 3);
        map.put("current", mPageIndex);
        map.put("firstType", firstType);
        APIManager.getInstance().create(CentralizedMiningAPI.class).getFactoryCentralizedList(map).enqueue(new ICallBack<BaseEntity<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>>>(true) {
            @Override
            public void onSuccess(BaseEntity<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showList(data.getData().getList(), b);
                } else {
                    MToast.showToast(fragment.getContext(), data.getMsg());
                }
            }
        });
    }

    public void getH5Url(String id) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().create(PickAPI.class).getUrlSetting("Factory").enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {//type 0 首页 1 我的集采 2 我的报价
                    SharedPreferenceUtil.init(fragment.getActivity());
                    String url = response.body().getData().getUrl() + "?id=" + id;
                    fragment.showUrl(url);
                } else {
                    MToast.showToast(fragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 拍卖详情页
     * @param no
     */
    public void getWebView(String no) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(false);
        BaseApi.getApi().getUrlSetting("Auctiondetails").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getState().equals(BaseApi.RESPONSE_OK)) {
                    String webUrl = data.getData().getUrl() + "?no=" + no;
                    BaseApi.startWeb(fragment.getActivity(), webUrl,123456);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 拍卖大厅列表
     */
    public void AuctionHallList(String typeNo, boolean isLoadMore) {
        page = isLoadMore ? page + 1 : 1;
        RequestBean requestBean = new RequestBean();
        requestBean.setState(typeNo);
        String longitudes;//经度
        String latitudes;//纬度
        longitudes = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        latitudes = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        if (TextUtils.isEmpty(longitudes)) {
            longitudes = "0";
        }
        if (TextUtils.isEmpty(latitudes)) {
            latitudes = "0";
        }
        requestBean.setLocalLat(latitudes);
        requestBean.setLocalLng(longitudes);
        requestBean.page = page;
        requestBean.limit = 6;
        BaseApi.getApi().getAuctionHallList(requestBean).enqueue(new ICallBack<BaseEntity<ListResponse<List<AuctionListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<AuctionListEntity>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getState().equals(BaseApi.RESPONSE_OK)) {
                    fragment.showList(data.getData().getList(), isLoadMore);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 获取拍卖tab页签方法
     */
    public void getAuctionHallTabList() {
        BaseApi.getApi().getAuctionStateSelect().enqueue(new ICallBack<BaseEntity<List<PublishListBean>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PublishListBean>> data) {
                if (data == null || data.getState() == null) {
                    fragment.showTypeData(new ArrayList<>());
                    return;
                }
                if (data.getState().equals(BaseApi.RESPONSE_OK)){
                    List<MenuEntity> listMenu = new ArrayList<>();
                    for (PublishListBean datum : data.getData()) {
                        listMenu.add(new MenuEntity(datum.getNo(),datum.getName()));
                    }
                    fragment.showTypeData(listMenu);
                }
            }
        });
    }
}
